package com.my12306.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * spring上下文工具类
 *
 * @Author:苏牧夕
 * @Date:2020/5/13 15:38
 * @Version 1.0
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {
    public static ApplicationContext applicationContext;

    /**
     * 根据bean的名字获取bean实例
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    /**
     * 根据name和类型获取bean
     *
     * @param name
     * @param calssType
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> calssType) {
        return applicationContext.getBean(name, calssType);
    }

    /**
     * 根据类型获取bean
     *
     * @param classType
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> classType) {
        return applicationContext.getBean(classType);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }

}
